(function($) {
    // page /stylebook
    if ($('[ng-app="stylebook"]').length) {
        var stylebook = angular.module('stylebook', ['ngSanitize', 'ngAnimate']);
        stylebook.controller('stylebookController', ['$scope', '$timeout', '$http',
            function($scope, $timeout, $http) {
            // debug use
            window.$scope = $scope;
            // init vars
            $scope.popupingBrand = false;
            $scope.searchBrand = '';
            $scope.brandLoading = false;
            $scope.brand = '';
            $scope.brands = [];
            var url = new URI(location.href);
            angular.element(document).ready(function() {
                var $body = $('body');
                $scope.$watch('popupingBrand', function(nv, ov) {
                    // add body class to disable page scroll
                    if (nv) {
                        $body.addClass('no-scroll');
                    } else {
                        $body.removeClass('no-scroll');
                    }
                }, true);
            });

            function updateBrand() {
                $http({
                    method: 'GET',
                    url: '/api/v1/brand?query=' + $scope.searchBrand
                }).then(function(res) {
                    // console.log(res);
                    $scope.brands = res.data;
                    $scope.brandLoading = false;
                }, function(res) {
                    console.error('Error while getting brands', res);
                    $scope.brandLoading = false;
                });
            }
            $scope.$watch('searchBrand', function(nv, ov) {
                (_.debounce(function() {
                    if (nv !== ov) {
                        $scope.brandLoading = true;
                        updateBrand();
                    }
                }, 300)());
            }, true);
            $scope.selectBrand = function(b) {
                url.setQuery('brand', b.tid).normalize();
                window.location.href = url.toString();
            }
            document.addEventListener('keyup', onKeyup, false);

            function onKeyup(e) {
                if (e.keyCode === 27) {
                    $scope.popupingBrand = false;
                    $scope.$apply();
                }
            }
            updateBrand();
        }]);
    }
    // authors
    if ($('[ng-app="authors"]').length) {
        var uri = new URI();
        var uid = uri.segment(1);
        var date = uri.segment(2) || 'all';
        var authors = angular.module('authors', ['ngSanitize', 'ngAnimate']);
        authors.filter('date1', function() {
            return function(item) {
                return moment(item, 'YYYYMM').format('MMMM YYYY');
            };
        });
        authors.filter('to_trusted', ['$sce', function($sce) {
            return function(text) {
                return $sce.trustAsHtml(text);
            };
        }]);
        authors.factory('authorsFactory', ['$q', '$timeout', '$http', '$rootScope',
            function($q, $timeout, $http, $rootScope) {
                var apiBase = '/jessica/api/';
                var api = {
                    content: apiBase + 'restapi_views/author_content?display_id=embed_1&args[]=' + uid + '&args[]=' + date,
                    sidebar: apiBase + 'restapi_block_region/sidebar_first'
                };
                $rootScope.contentPage = 0;

                function getContent() {
                    var defer = $q.defer();
                    $http({
                        method: 'GET',
                        url: api.content + '&page=' + $rootScope.contentPage
                    }).then(function(res) {
                        defer.resolve(res);
                    }, function(err) {
                        console.error(err);
                        defer.reject();
                    });
                    return defer.promise;
                }

                function getSidebar() {
                    var defer = $q.defer();
                    $http({
                        method: 'GET',
                        url: api.sidebar
                    }).then(function(res) {
                        defer.resolve(res);
                    }, function(err) {
                        console.error(err);
                        defer.reject();
                    })
                    return defer.promise;
                }
                return {
                    getContent: getContent,
                    getSidebar: getSidebar
                };
            }
        ]);
        authors.controller('contentCtrl', ['$scope', 'authorsFactory', '$timeout', '$rootScope',
            function($scope, authorsFactory, $timeout, $rootScope) {
                window.$scope = $scope;
                $scope.loading = true;
                $scope.contentReady = false;
                $scope.domReady = false;
                $scope.perpetualReady = false;
                $scope.$watchGroup(['contentReady', 'domReady'], function(nv, ov) {
                    if ($scope.contentReady && $scope.domReady && !$scope.perpetualReady) {
                        initPerpetual();
                    }
                });

                function initPerpetual() {
                    var $win = $(window);
                    var triggerArea = 100;
                    var winst = $win.scrollTop();
                    var winH = $win.height();
                    var $footer = $('.region-bottom');
                    var hitBottom = false;

                    function checkHitBottom() {
                        winst = $win.scrollTop();
                        winH = $win.height();
                        // check hit bottom & load new content
                        if (winst + winH + triggerArea >= $footer.position().top) {
                            if (!hitBottom) {
                                $scope.loading = true;
                                hitBottom = true;
                                // console.log('hit bottom');
                                // get & append content
                                authorsFactory.getContent().then(function(res) {
                                    // console.log(res.data.content);
                                    $scope.content = $scope.content.concat(res.data.content);
                                    $scope.loading = false;
                                    $rootScope.contentPage++;
                                });
                            }
                        } else {
                            hitBottom = false;
                        }
                    }
                    $win.on('load scroll', (_.debounce(checkHitBottom, 100)));
                    perpetualReady = true;
                }
                authorsFactory.getContent().then(function(res) {
                    // console.log(res.data.content);
                    $scope.content = res.data.content;
                    $rootScope.contentPage++;
                    $scope.loading = false;
                    $scope.contentReady = true;
                });
                angular.element(document).ready(function() {
                    $scope.domReady = true;
                });
            }
        ]);
        authors.controller('sidebarCtrl', ['$scope', 'authorsFactory', '$timeout',
            function($scope, authorsFactory, $timeout) {
                window.$scope = $scope;
                authorsFactory.getSidebar().then(function(res) {
                    // console.log(res.data);
                    $scope.sidebar = res.data;
                });
            }
        ]);
    }
    // page msw
    if ($('[ng-app="msw"]').length) {
        var msw = angular.module('msw', ['ngSanitize', 'ngAnimate', 'checklist-model']);
        msw.filter('to_url', function() {
            return function(item) {
                var el = $(item);
                if (el.is('[href]')) {
                    return el.attr('href');
                } else if (el.is('[src]')) {
                    return el.attr('src');
                }
                return item;
            };
        });
        msw.filter('to_text', function() {
            return function(item) {
                var el = $(item);
                return el.text();
            }
        });
        msw.factory('mswFactory', ['$q', '$http', '$timeout',
            function($q, $http, $timeout) {
                var apiBase = '/jessica/api/';
                var api = {
                    search: apiBase + 'restapi_views/msw_home',
                    industry: apiBase + 'restapi_views/msw_industry',
                    mostview: apiBase + 'restapi_views/msw_home?display_id=block_1'
                };

                function getIndustry() {
                    var defer = $q.defer();
                    $http({
                        method: 'GET',
                        url: api.industry
                    }).then(function(res) {
                        defer.resolve(res.data.content);
                    }, function(err) {
                        console.error(err);
                        defer.reject();
                    });
                    return defer.promise;
                }

                function getMostview() {
                    var defer = $q.defer();
                    $http({
                        method: 'GET',
                        url: api.mostview
                    }).then(function(res) {
                        defer.resolve(res.data.content);
                    }, function(err) {
                        console.error(err);
                        defer.reject();
                    });
                    return defer.promise;
                }

                function search(params) {
                    var defer = $q.defer();
                    $http({
                        method: 'GET',
                        url: api.search + params
                    }).then(function(res) {
                        defer.resolve(res.data.content);
                    }, function(err) {
                        console.error(err);
                        defer.reject();
                    });
                    return defer.promise;
                }

                return {
                    getIndustry: getIndustry,
                    getMostview: getMostview,
                    search: search
                }
            }
        ]);

        msw.controller('mswCtrl', ['$scope', 'mswFactory', '$timeout',
            function($scope, mswFactory, $timeout) {
                window.$scope = $scope;


                $scope.hasFilter = false;
                $scope.loading = true;
                mswFactory.getMostview().then(function(res) {
                    $scope.mostview = res;
                    $scope.loading = false;
                });

                $scope.alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
                mswFactory.getIndustry().then(function(content) {
                    $scope.industry = content;
                });
                $scope.selected = {
                    alphabet: [],
                    industry: []
                };
                $scope.searchText = '';

                $scope.reset = function() {
                    $scope.selected = {
                        alphabet: [],
                        industry: []
                    };
                    $scope.searchText = '';
                    $scope.hasFilter = false;
                    $scope.loading = false;
                }

                $scope.onKeyup = function(e) {
                    if (e.keyCode === 13) {
                        $scope.search();
                    }
                }

                $scope.search = function() {
                    if ($scope.selected.alphabet.length === 0
                        && $scope.selected.industry.length === 0
                        && $scope.searchText.length === 0) {
                        $scope.hasFilter = false;
                        return;
                    }

                    $scope.hasFilter = true;
                    $scope.loading = true;

                    if ($scope.selected.alphabet.length) {
                        uri.setSearch('alphabetic_search[]', $scope.selected.alphabet);
                    } else {
                        uri.removeSearch('alphabetic_search[]');
                    }

                    if ($scope.selected.industry.length) {
                        uri.setSearch('field_industry_tid[]', $scope.selected.industry);
                    } else {
                        uri.removeSearch('field_industry_tid[]');
                    }

                    if ($scope.searchText.length) {
                        uri.setSearch('field_msw_english_name_value', $scope.searchText);
                    } else {
                        uri.removeSearch('field_msw_english_name_value');
                    }

                    mswFactory.search(uri.readable()).then(function(res) {
                        $scope.searchResult = res;
                        $scope.loading = false;
                    });
                }

                var uri = new URI('?display_id=page');
                $scope.$watch('selected', function(nv,ov) {
                    if (nv !== ov) {
                        $scope.search();
                    }
                }, true);

            }
        ]);
    }
})(jQuery);
